<?php

include('cfg/def.php');
include('cfg/cfg.php');

include_once("lib/logger.class.php");
include_once("lib/mysql.class.php");
include_once("models/m_user.class.php");
include_once("models/m_city.class.php");
include_once("models/m_events.class.php");
include_once("models/m_event_links.class.php");
include_once("models/m_search.class.php");

Logger::$log_file = $log_midp_name;

MySQL::$url = $dburl;
MySQL::$encoding = $def_encoding;

session_start();

if(DEBUG_MODE)
{
	//Logger::Write(__FILE__." line ".__LINE__, 'RAW: '.$HTTP_RAW_POST_DATA);
	Logger::Write(__FILE__." line ".__LINE__, '$_GET: '.print_r($_GET, true));
	Logger::Write(__FILE__." line ".__LINE__, '$_POST: '.print_r($_POST, true));
}

$xml = $_POST["xml"];
$xml = stripslashes($xml);
Logger::Write(__FILE__." line ".__LINE__, 'AJAX REQUEST: '.$xml);



$pack_a = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><pack />');
$ans = $pack_a->addChild("ans");
try
{
	// Пакет запроса
	$pack_r = new SimpleXMLElement($xml);
}
catch(Exception $e)
{
	$ans->addAttribute("err", $e->getMessage());
	$pack_r = null;
}

Logger::Write("MIDP", "req count: ".count($pack_r->req));
if($pack_r && (count($pack_r->req) == 1))
{
	$req = $pack_r->req[0];
	$obj  = (string)$req["o"];
	$act  = (string)$req["a"];
	$mail = (string)$req["m"];
	$pass = (string)$req["p"];
	
	$ans->addAttribute("id", $req["id"]);
	$ans->addAttribute("o", $obj);
	$ans->addAttribute("a", $act);
	
	$data = nodes2arr($req->p);
	
	$actor = new mUser();
	if($actor->login($mail, $pass))
	{
		$ans->addAttribute("ecode", "0");
		$ans->addAttribute("error", "");
		switch($obj)
		{
			case 'user':
				// $actor->load();
				switch($act)
				{
					case "login":
						$n = $ans->addChild("n");
						$n->addAttribute("uid", $actor->id);
						$n->addAttribute("cid", $actor->props["city_id"]);
						$n->addAttribute("news", $actor->news_num);
						$n->addAttribute("name", $actor->props["username"]);
						$n->addAttribute("mail", $actor->props["mail"]);
						$n->addAttribute("city", $actor->props["city"]);
						$n->addAttribute("note", $actor->props["note"]);
						break;
					
					case "links":
						$user_id = empty($data["user_id"]) ? $actor->id : $data["user_id"];
						$users = mUser::get_links($user_id);
						$ids = implode(",", $users[$data["link"]]);
						$users = mUser::get_props($ids, TRUE);
						if($users)
							foreach($users as $u)
							{
								$n = $ans->addChild("n");
								$n->addAttribute("id", $u["id"]);
								$n->addAttribute("name", $u["username"]);
								$n->addAttribute("city", $u["city"]);
								$n->addAttribute("born", $u["born"]);
								$n->addAttribute("note", $u["note"]);
							}
						break;
					
					case "find":
						$users = mSearch::get_users($data["find"], 20);
						$ids = implode(",", $users);
						$users = mUser::get_props($ids, TRUE);
						foreach($users as $u)
						{
							$n = $ans->addChild("n");
							$n->addAttribute("id", $u["id"]);
							$n->addAttribute("name", $u["username"]);
							$n->addAttribute("city", $u["city"]);
							$n->addAttribute("born", $u["born"]);
							$n->addAttribute("note", $u["note"]);
						}
						break;
				}
				break;
			
			case 'country':
				switch($act)
				{
					case 'get':
						$geo = new mCity();
						$rows = $geo->get_countries();
						foreach($rows as $row)
						{
							$n = $ans->addChild("n");
							$n->addAttribute("id", $row["id"]);
							$n->addAttribute("name", $row["name"]);
						}
						break;
				}
				break;
			
			case 'region':
				switch($act)
				{
					case 'get':
						$geo = new mCity();
						$rows = $geo->get_regions($data["country_id"]);
						foreach($rows as $row)
						{
							$n = $ans->addChild("n");
							$n->addAttribute("id", $row["id"]);
							$n->addAttribute("name", $row["name"]);
						}
						break;
				}
				break;
			
			case 'city':
				switch($act)
				{
					case 'get':
						$geo = new mCity();
						$rows = $geo->get_cities($data["region_id"]);
						foreach($rows as $row)
						{
							$n = $ans->addChild("n");
							$n->addAttribute("id", $row["id"]);
							$n->addAttribute("name", $row["name"]);
						}
						break;
				}
				break;
			
			case "links":
				// $link_groups = mUser::get_links($actor->id);
				$link_groups = $actor->links;
				$actor->load_users();
				switch($act)
				{
					case "get":
						$ans->addAttribute("type", "list");
						foreach($link_groups as $key => $group)
						{
							foreach($group as $link)
							{
								$u = $ans->addChild("link");
								$u->addAttribute("cat", $key);
								$u->addAttribute("uid", $link);
								$u->addAttribute("name", $actor->users[$link]["username"]);
							}
						}
						break;
				}
				break;
			
			case "plan":
				switch($act)
				{
					case "get":
						$c = strtolower($data["categ"]);
						$sha = (bool)($c == 'sha');
						$sub = (bool)($c == 'sub');
						$own = (bool)($c == 'own');
						
						Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, '$data["city_id"] = ['.$data["city_id"].']');
						
						$beg = empty($data["beg"]) ? 0 : (int)$data["beg"];
						$num = empty($data["num"]) ? NUM_ROWS : (int)$data["num"];
						$ord = empty($data["desc"]) ? TRUE : (bool)($data["desc"] == "0");
						$sql = mEvents::generate_sql($actor->id, $data["user_id"], $data["city_id"], $data["date"], $sha, $sub, $own);
						$events = mEvents::read($sql, $beg, $num, $ord, $actor->id);
						// $events = mEvents::add_details($events, $actor->id);
						$ans->addAttribute("type", "list");
						
						foreach($events as $e)
						{
							$n = $ans->addChild("n", $e["note"]);
							$n->addAttribute("id", $e["event_id"]);
							$n->addAttribute("city", $e["city"]);
							$n->addAttribute("city_id", $e["city_id"]);
							$n->addAttribute("user", $e["username"]);
							$n->addAttribute("user_id", $e["user_id"]);
							$n->addAttribute("date", $e["dt_beg"]);
							$n->addAttribute("num_com", $e["num_com"]);
							$n->addAttribute("num_sha", $e["num_sha"]);
							
							// $parts = array('У','Д','В','Н');
							$parts = "";
							for($i = 0; $i < 4; $i++)
								$parts .= ($e["part_".$i] == 'Y') ? '1' : '0';
							$n->addAttribute("parts", $parts);
						}
						break;
					
					case 'find':
						$events = mSearch::get_events($data["find"], $actor, $data["date"], $data["city_id"]);
						$ans->addAttribute("type", "list");
						
						foreach($events as $e)
						{
							$n = $ans->addChild("n", $e["note"]);
							$n->addAttribute("id", $e["event_id"]);
							$n->addAttribute("city", $e["city"]);
							$n->addAttribute("city_id", $e["city_id"]);
							$n->addAttribute("user", $e["username"]);
							$n->addAttribute("user_id", $e["user_id"]);
							$n->addAttribute("date", $e["dt_beg"]);
							$n->addAttribute("num_com", $e["num_com"]);
							$n->addAttribute("num_sha", $e["num_sha"]);
							
							// $parts = array('У','Д','В','Н');
							$parts = "";
							for($i = 0; $i < 4; $i++)
								$parts .= ($e["part_".$i] == 'Y') ? '1' : '0';
							$n->addAttribute("parts", $parts);
						}
						break;
				}
				break;
		}
	}
	else
	{
		$ans->addAttribute("err", "Неверный адрес эл.почты или пароль");
		$ans->addAttribute("ecode", "2");
	}
}
else
{
	if($pack_r)
	{
		$ans->addAttribute("err", "Неверный формат пакета");
		$ans->addAttribute("ecode", "1");
	}
}

$xml = $pack_a->asXML();

if(DEBUG_MODE)
{
	global $log_file_name;
	$fd = fopen($log_midp_name.".xml.".date('Ymd').".log", "w+");
	// fwrite($fd, htmlspecialchars_decode($xml));
	fwrite($fd, $xml);
	fclose($fd);
}

header('Content-Type: text/xml; charset=utf-8');
echo $xml;
exit();


function attr2arr($node)
{
	$a = array();
	foreach($node->attributes() as $k => $v)
		$a[$k] = Utils::val($v);
	return $a;
}

function nodes2arr($nodes)
{
	$a = array();
	if(empty($nodes)) return $a;
	foreach($nodes as $child)
		$a[(string)$child["n"]] = html_entity_decode(Utils::val((string)$child["v"]), ENT_QUOTES);
	/*
	foreach($node->children() as $child)
		$a[(string)$child["name"]] = Utils::val((string)$child["value"]);
	*/
	return $a;
}





